package com.css.bjdt_report.report.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.css.bjdt_report.cell.entity.Cell;
import com.css.bjdt_report.cell.service.CellService;
import com.css.bjdt_report.report.entity.RptAreaTemporary;
import com.css.bjdt_report.report.entity.RptTemplateStatCategory;
import com.css.bjdt_report.report.entity.ViewRptGroupTemplate;
import com.css.bjdt_report.report.service.ReportDesignService;
import com.css.bjdt_report.report.service.ReportStatCategoryService;
import com.css.bjdt_report.report.service.ReportTemplateManageService;
import com.css.bjdt_report.report.service.RptAreaCategoryRService;
import com.css.bjdt_report.report.service.RptAreaTemporaryService;
import com.css.bjdt_report.util.CommonUtil;
import com.css.bjdt_report.util.JsonResult;

@Controller
@RequestMapping(value = "/reportDesignController")
public class ReportDesignController {

	@Autowired
	private CellService cellService;

	@Autowired
	private RptAreaTemporaryService rptAreaTemporaryService;

	@Autowired
	private ReportStatCategoryService reportStatCategoryService;

	@Autowired
	private ReportTemplateManageService reportTemplateManageService;

	@Autowired
	private RptAreaCategoryRService rptAreaCategoryRService;

	@Autowired
	private ReportDesignService reportDesignService;

	@RequestMapping(value = "/preReportDesign/{templateId}/{annualId}", method = RequestMethod.GET)
	public String preCreateReportGroup(@PathVariable String templateId, @PathVariable String annualId, Model model) {
		model.addAttribute("templateId", templateId);
		model.addAttribute("annualId", annualId);
		RptAreaTemporary rptAreaTemporary = rptAreaTemporaryService.getRptAreaTemporary(templateId);
		if (rptAreaTemporary != null) {
			model.addAttribute("condStartCol", rptAreaTemporary.getCondStartCol());
			model.addAttribute("condEndCol", rptAreaTemporary.getCondEndCol());
			model.addAttribute("condStartRow", rptAreaTemporary.getCondStartRow());
			model.addAttribute("condEndRow", rptAreaTemporary.getCondEndRow());
			model.addAttribute("absStartCol", rptAreaTemporary.getAbsStartCol());
			model.addAttribute("absEndCol", rptAreaTemporary.getAbsEndCol());
			model.addAttribute("absStartRow", rptAreaTemporary.getAbsStartRow());
			model.addAttribute("absEndRow", rptAreaTemporary.getAbsEndRow());
		}
		return "/report-design/report-template-design";
	}

	@RequestMapping(value = "/preReportCommentDesign/{templateId}/{annualId}", method = RequestMethod.GET)
	public String preCreateReportComment(@PathVariable String templateId, @PathVariable String annualId, Model model) {
		model.addAttribute("templateId", templateId);
		model.addAttribute("annualId", annualId);
		RptAreaTemporary rptAreaTemporary = rptAreaTemporaryService.getRptAreaTemporary(templateId);
		if (rptAreaTemporary != null) {
			model.addAttribute("condStartCol", rptAreaTemporary.getCondStartCol());
			model.addAttribute("condEndCol", rptAreaTemporary.getCondEndCol());
			model.addAttribute("condStartRow", rptAreaTemporary.getCondStartRow());
			model.addAttribute("condEndRow", rptAreaTemporary.getCondEndRow());
			model.addAttribute("absStartCol", rptAreaTemporary.getAbsStartCol());
			model.addAttribute("absEndCol", rptAreaTemporary.getAbsEndCol());
			model.addAttribute("absStartRow", rptAreaTemporary.getAbsStartRow());
			model.addAttribute("absEndRow", rptAreaTemporary.getAbsEndRow());
		}
		//得到统计信息集
		RptTemplateStatCategory rptTemplateStatCategory = reportStatCategoryService
				.getStatCategoryByTemplateId(templateId).get(0);
		if (rptTemplateStatCategory != null) {
			model.addAttribute("dataSetSelectId", rptTemplateStatCategory.getSetId());
			model.addAttribute("dataItemSelectId", rptTemplateStatCategory.getItemId());
			model.addAttribute("itemStatTimeSelectId", rptTemplateStatCategory.getItemStatTimeId());
			model.addAttribute("itemUnitIdSelectId", rptTemplateStatCategory.getItemUnitId());
		}
		return "/report-design/report-template-comment-design";
	}

	//保存报表模板
	@RequestMapping(value = "/saveReportTemplate/{templateId}/{annualId}", method = RequestMethod.POST)
	public void saveReportTemplate(@PathVariable String templateId, @PathVariable String annualId,
			HttpServletRequest request) {
		String url = CommonUtil.readProperties();
		//String uploadPath = getUploadPath(request);
		File directory = new File(url, annualId);
		if (!directory.exists()) {
			directory.mkdir();
		}
		String fileName = templateId + ".cll";
		File cellFile = new File(directory.getPath(), fileName);
		if (cellFile.exists()) {
			cellFile.delete();
		}
		try {
			FileUtils.copyInputStreamToFile(request.getInputStream(), cellFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/readReportTemplate/{templateId}/{annualId}")
	public void readReportTemplate(@PathVariable String templateId, @PathVariable String annualId,
			HttpServletRequest request, HttpServletResponse res) {
		String url = CommonUtil.readProperties();
		//String uploadPath = getUploadPath(request);
		String fileName = templateId + ".cll";
		File cellFile = new File(url + "/" + annualId + "/", fileName);
		if (cellFile.exists()) {
			OutputStream os = null;
			try {
				os = res.getOutputStream();
				os.write(FileUtils.readFileToByteArray(cellFile));
				os.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (os != null) {
					try {
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	private String getUploadPath(HttpServletRequest request) {
		//return request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
		return request.getSession().getServletContext().getRealPath("");
	}

	//保存单元格属性
	@ResponseBody
	@RequestMapping(value = "/saveReportAllCellType/{templateId}/{annualId}", method = RequestMethod.POST)
	public void saveReportAndCellType(@PathVariable String templateId, @PathVariable String annualId,
			@RequestParam(value = "jsonText") String cellTypeJson,
			@RequestParam(value = "reportCategoryText") String reportCategoryText, Model model) {
		try {
			List<RptAreaTemporary> rptAreaTemporaryList = new ArrayList<RptAreaTemporary>();
			//解析报表的数据区域
			JsonResult reportCategoryResult = new JsonResult();
			Map<String, String> reportCategoryMap = reportCategoryResult.jsonToString(reportCategoryText);
			Set<String> reportCategoryKey = reportCategoryMap.keySet();
			for (String strKey : reportCategoryKey) {
				String strJson = "{" + reportCategoryMap.get(strKey) + "}";
				JSONObject reportCategoryJobj = new JSONObject(strJson);
				String categoryId = reportCategoryJobj.getString("categoryId");
				String condStartCol = reportCategoryJobj.getString("condStartCol");
				String condEndCol = reportCategoryJobj.getString("condEndCol");
				String condStartRow = reportCategoryJobj.getString("condStartRow");
				String condEndRow = reportCategoryJobj.getString("condEndRow");
				String absStartCol = reportCategoryJobj.getString("absStartCol");
				String absEndCol = reportCategoryJobj.getString("absEndCol");
				String absStartRow = reportCategoryJobj.getString("absStartRow");
				String absEndRow = reportCategoryJobj.getString("absEndRow");
				String temporaryDescribe = reportCategoryJobj.getString("temporaryDescribe");
				//先塞数据区域的东西
				RptAreaTemporary rptAreaTemporary = new RptAreaTemporary();
				rptAreaTemporary.setId(CommonUtil.getUUID());
				rptAreaTemporary.setTemplateId(templateId);
				rptAreaTemporary.setCondStartCol(condStartCol);
				rptAreaTemporary.setCondEndCol(condEndCol);
				rptAreaTemporary.setCondStartRow(condStartRow);
				rptAreaTemporary.setCondEndRow(condEndRow);
				rptAreaTemporary.setAbsStartCol(absStartCol);
				rptAreaTemporary.setAbsEndCol(absEndCol);
				rptAreaTemporary.setAbsStartRow(absStartRow);
				rptAreaTemporary.setAbsEndRow(absEndRow);
				rptAreaTemporary.setCategoryId(categoryId);
				rptAreaTemporary.setTemporaryDescribe(temporaryDescribe);
				rptAreaTemporaryList.add(rptAreaTemporary);
			}

			//再塞单元格的属性
			List<Cell> cellList = new ArrayList<Cell>();
			JsonResult jsonResult = new JsonResult();
			Map<String, String> map = jsonResult.jsonToString(cellTypeJson);
			Set<String> key = map.keySet();
			for (String strKey : key) {
				String strJson = "{" + map.get(strKey) + "}";
				JSONObject jobj = new JSONObject(strJson);
				Cell cell = new Cell();
				cell.setTemplateId(templateId);
				cell.setAbsColNum(Integer.parseInt(jobj.getString("absolutelyCol")));
				cell.setAbsRowNum(Integer.parseInt(jobj.getString("absolutelyRow")));
				if (jobj.getString("relColNum") != null && !("".equals(jobj.getString("relColNum")))
						&& !("null").equals(jobj.getString("relColNum"))) {
				System.out.println(strJson);
					cell.setRelColNum(Integer.parseInt(jobj.getString("relColNum")));
				}
				if (jobj.getString("relRowNum") != null && !("".equals(jobj.getString("relRowNum")))
						&& !("null").equals(jobj.getString("relRowNum"))) {
					cell.setRelRowNum(Integer.parseInt(jobj.getString("relRowNum")));
				}
				cell.setCellType(jobj.getString("cellType"));
				cell.setIsComment(jobj.getString("isComment"));
				if (jobj.getString("presetType") == null || "".equals(jobj.getString("presetType"))) {
					cell.setQuoteType("");
				} else {
					cell.setQuoteType(jobj.getString("presetType"));
				}
				//判断区域性质
				if (jobj.getString("areaType") == null || "".equals(jobj.getString("areaType"))) {
					if (cell.getRelColNum() != null && cell.getRelRowNum() != null) {
						cell.setAreaType("1");
					} else {
						cell.setAreaType("2");
					}
				} else {
					cell.setAreaType(jobj.getString("areaType"));
				}
				cellList.add(cell);
			}
			reportDesignService.saveRptAreaCategoryCell(cellList, rptAreaTemporaryList, templateId);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//通过报表ID，获得当前报表单元格的所有属性
	@ResponseBody
	@RequestMapping(value = "/queryReportAndCellType/{templateId}", method = RequestMethod.POST)
	public List<Cell> queryReportAndCellType(@PathVariable String templateId) {
		List<Cell> cellList = cellService.getCellsByTemplateId(templateId);
		return cellList;
	}

	//通过报表ID，获得当前报表单元格的所有数据区域
	@ResponseBody
	@RequestMapping(value = "/queryReportAreaTemporary/{templateId}", method = RequestMethod.POST)
	public List<RptAreaTemporary> queryReportAreaTemporary(@PathVariable String templateId) {
		List<RptAreaTemporary> rptAreaTemporaryList = rptAreaTemporaryService.queryRptAreaTemporaryList(templateId);
		List<RptAreaTemporary> rptAreaTemporaryListNew = new ArrayList<RptAreaTemporary>();
		for (RptAreaTemporary rptAreaTemporary : rptAreaTemporaryList) {
			String categoryId = rptAreaCategoryRService.getCategoryIdByAreaId(rptAreaTemporary.getId());
			RptTemplateStatCategory rptTemplateStatCategory = reportStatCategoryService
					.getAReportStatCategoryById(categoryId);
			rptAreaTemporary.setCategoryId(categoryId);
			rptAreaTemporary.setCategoryName(rptTemplateStatCategory.getCategoryName());
			rptAreaTemporaryListNew.add(rptAreaTemporary);
		}
		return rptAreaTemporaryListNew;
	}

	/*@RequestMapping("/readReportTemplate/{condStartColValueHidden}/{condEndColValueHidden}/{condStartRowValueHidden}/{condEndRowValueHidden}")
	public String toSetUpCondPage(@PathVariable String condStartColValueHidden,
			@PathVariable String condEndColValueHidden, @PathVariable String condStartRowValueHidden,
			@PathVariable String condEndRowValueHidden, Model model) {
		String[] letterArray = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q",
				"R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI" };
		Map<Integer, String> colMap = new HashMap<Integer, String>();
		for (int a = Integer.parseInt(condStartColValueHidden); a < Integer.parseInt(condEndColValueHidden) + 1; a++) {
			String letter = letterArray[a - 1];
			colMap.put(a, letter);
		}
		model.addAttribute("colMap", colMap);
		return "/report-design/report-template-conditions";
	}*/

	//得到所有的报表信息
	@ResponseBody
	@RequestMapping(value = "/getAllTemplateInfo/{annualId}", method = RequestMethod.POST)
	public List<ViewRptGroupTemplate> getAllTemplateInfo(@PathVariable String annualId) {
		return reportTemplateManageService.getRptTemplateByAnnualId(annualId);
	}

}
